// 测试历史记录管理工具

/**
 * 保存测试记录
 * @param {string} testType - 测试类型 (memory, reaction, chimp, visual, typing)
 * @param {object} testData - 测试数据
 */
export const saveTestRecord = (testType, testData) => {
  try {
    const historyKey = `${testType}_test_history`
    let history = getTestHistory(testType)
    
    // 添加时间戳和唯一ID
    const record = {
      id: Date.now().toString(),
      timestamp: new Date().toISOString(),
      date: new Date().toLocaleDateString('zh-CN'),
      time: new Date().toLocaleTimeString('zh-CN'),
      ...testData
    }
    
    history.unshift(record)
    
    // 只保留最近100条记录
    if (history.length > 100) {
      history = history.slice(0, 100)
    }
    
    uni.setStorageSync(historyKey, JSON.stringify(history))
    
    // 更新统计数据
    updateTestStats(testType, record)
    
    return record
  } catch (error) {
    console.error('保存测试记录失败:', error)
    return null
  }
}

/**
 * 获取测试历史记录
 * @param {string} testType - 测试类型
 * @param {number} limit - 限制条数
 * @returns {Array} 历史记录数组
 */
export const getTestHistory = (testType, limit = null) => {
  try {
    const historyKey = `${testType}_test_history`
    const stored = uni.getStorageSync(historyKey)
    let history = stored ? JSON.parse(stored) : []
    
    if (limit && limit > 0) {
      history = history.slice(0, limit)
    }
    
    return history
  } catch (error) {
    console.error('获取测试历史失败:', error)
    return []
  }
}

/**
 * 更新测试统计数据
 * @param {string} testType - 测试类型
 * @param {object} record - 测试记录
 */
const updateTestStats = (testType, record) => {
  try {
    const statsKey = `${testType}_test_stats`
    let stats = uni.getStorageSync(statsKey)
    
    if (!stats) {
      stats = {
        totalTests: 0,
        bestScore: 0,
        averageScore: 0,
        totalScore: 0,
        bestTime: null,
        averageTime: 0,
        totalTime: 0,
        lastTestDate: null,
        streak: 0,
        maxStreak: 0
      }
    }
    
    // 更新基础统计
    stats.totalTests += 1
    stats.lastTestDate = record.date
    
    // 根据测试类型更新特定统计
    switch (testType) {
      case 'memory':
        updateMemoryStats(stats, record)
        break
      case 'reaction':
        updateReactionStats(stats, record)
        break
      case 'chimp':
        updateChimpStats(stats, record)
        break
      case 'visual':
        updateVisualStats(stats, record)
        break
      case 'typing':
        updateTypingStats(stats, record)
        break
    }
    
    // 更新连续测试天数
    updateStreak(stats, record)
    
    uni.setStorageSync(statsKey, stats)
  } catch (error) {
    console.error('更新统计数据失败:', error)
  }
}

/**
 * 更新记忆力测试统计
 */
const updateMemoryStats = (stats, record) => {
  if (record.finalScore > stats.bestScore) {
    stats.bestScore = record.finalScore
  }
  
  stats.totalScore += record.finalScore
  stats.averageScore = Math.round(stats.totalScore / stats.totalTests)
  
  if (record.averageReactionTime) {
    if (!stats.bestTime || record.averageReactionTime < stats.bestTime) {
      stats.bestTime = record.averageReactionTime
    }
    
    stats.totalTime += record.averageReactionTime
    stats.averageTime = Math.round(stats.totalTime / stats.totalTests)
  }
}

/**
 * 更新反应力测试统计
 */
const updateReactionStats = (stats, record) => {
  if (record.averageTime) {
    if (!stats.bestTime || record.averageTime < stats.bestTime) {
      stats.bestTime = record.averageTime
    }
    
    stats.totalTime += record.averageTime
    stats.averageTime = Math.round(stats.totalTime / stats.totalTests)
  }
}

/**
 * 更新黑猩猩测试统计
 */
const updateChimpStats = (stats, record) => {
  if (record.finalScore > stats.bestScore) {
    stats.bestScore = record.finalScore
  }
  
  stats.totalScore += record.finalScore
  stats.averageScore = Math.round(stats.totalScore / stats.totalTests)
  
  if (record.averageReactionTime) {
    if (!stats.bestTime || record.averageReactionTime < stats.bestTime) {
      stats.bestTime = record.averageReactionTime
    }
    
    stats.totalTime += record.averageReactionTime
    stats.averageTime = Math.round(stats.totalTime / stats.totalTests)
  }
}

/**
 * 更新视觉测试统计
 */
const updateVisualStats = (stats, record) => {
  if (record.totalScore > stats.bestScore) {
    stats.bestScore = record.totalScore
  }
  
  stats.totalScore += record.totalScore
  stats.averageScore = Math.round(stats.totalScore / stats.totalTests)
}

/**
 * 更新打字测试统计
 */
const updateTypingStats = (stats, record) => {
  if (record.finalWPM > stats.bestScore) {
    stats.bestScore = record.finalWPM
  }
  
  stats.totalScore += record.finalWPM
  stats.averageScore = Math.round(stats.totalScore / stats.totalTests)
}

/**
 * 更新连续测试天数
 */
const updateStreak = (stats, record) => {
  const today = new Date().toLocaleDateString('zh-CN')
  const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000).toLocaleDateString('zh-CN')
  
  if (stats.lastTestDate === today) {
    // 今天已经测试过，不更新连续天数
    return
  } else if (stats.lastTestDate === yesterday) {
    // 昨天测试过，连续天数+1
    stats.streak += 1
  } else {
    // 中断了，重新开始
    stats.streak = 1
  }
  
  if (stats.streak > stats.maxStreak) {
    stats.maxStreak = stats.streak
  }
}

/**
 * 获取测试统计数据
 * @param {string} testType - 测试类型
 * @returns {object} 统计数据
 */
export const getTestStats = (testType) => {
  try {
    const statsKey = `${testType}_test_stats`
    const stats = uni.getStorageSync(statsKey)
    return stats || {
      totalTests: 0,
      bestScore: 0,
      averageScore: 0,
      bestTime: null,
      averageTime: 0,
      lastTestDate: null,
      streak: 0,
      maxStreak: 0
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    return {
      totalTests: 0,
      bestScore: 0,
      averageScore: 0,
      bestTime: null,
      averageTime: 0,
      lastTestDate: null,
      streak: 0,
      maxStreak: 0
    }
  }
}

/**
 * 获取所有测试的综合统计
 * @returns {object} 综合统计数据
 */
export const getAllTestStats = () => {
  const testTypes = ['memory', 'reaction', 'chimp', 'visual', 'typing']
  const allStats = {}
  
  let totalTests = 0
  let totalDays = new Set()
  
  testTypes.forEach(testType => {
    const stats = getTestStats(testType)
    allStats[testType] = stats
    totalTests += stats.totalTests
    
    // 收集测试日期
    const history = getTestHistory(testType)
    history.forEach(record => {
      totalDays.add(record.date)
    })
  })
  
  return {
    ...allStats,
    totalTests,
    totalDays: totalDays.size,
    testTypes: testTypes.length
  }
}

/**
 * 获取测试趋势数据
 * @param {string} testType - 测试类型
 * @param {number} days - 天数
 * @returns {Array} 趋势数据
 */
export const getTestTrend = (testType, days = 7) => {
  try {
    const history = getTestHistory(testType)
    const trend = []
    
    for (let i = days - 1; i >= 0; i--) {
      const date = new Date(Date.now() - i * 24 * 60 * 60 * 1000).toLocaleDateString('zh-CN')
      const dayRecords = history.filter(record => record.date === date)
      
      let dayData = {
        date,
        count: dayRecords.length,
        averageScore: 0,
        bestScore: 0
      }
      
      if (dayRecords.length > 0) {
        const scores = dayRecords.map(record => {
          switch (testType) {
            case 'memory':
            case 'chimp':
              return record.finalScore || 0
            case 'visual':
              return record.totalScore || 0
            case 'typing':
              return record.finalWPM || 0
            case 'reaction':
              return record.averageTime || 0
            default:
              return 0
          }
        })
        
        dayData.averageScore = Math.round(scores.reduce((a, b) => a + b, 0) / scores.length)
        dayData.bestScore = testType === 'reaction' ? Math.min(...scores) : Math.max(...scores)
      }
      
      trend.push(dayData)
    }
    
    return trend
  } catch (error) {
    console.error('获取趋势数据失败:', error)
    return []
  }
}

/**
 * 清除测试历史记录
 * @param {string} testType - 测试类型
 */
export const clearTestHistory = (testType) => {
  try {
    const historyKey = `${testType}_test_history`
    const statsKey = `${testType}_test_stats`
    
    uni.removeStorageSync(historyKey)
    uni.removeStorageSync(statsKey)
    
    return true
  } catch (error) {
    console.error('清除历史记录失败:', error)
    return false
  }
}

/**
 * 导出测试数据
 * @param {string} testType - 测试类型
 * @returns {object} 导出的数据
 */
export const exportTestData = (testType) => {
  try {
    const history = getTestHistory(testType)
    const stats = getTestStats(testType)
    
    return {
      testType,
      exportDate: new Date().toISOString(),
      stats,
      history
    }
  } catch (error) {
    console.error('导出数据失败:', error)
    return null
  }
}